<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectModel;
use app\app\model\ProjectTDModel;
use app\app\model\ProjectZrrDetailModel;
use app\app\model\ProjectZrrModel;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;

class ProjectZrr extends BaseController
{
    /**
     * 责任人导入
     * @return void
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function import()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'zrr', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name, 1);

        $insert_array = [];
        $error_array = [];
        $i = 0;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;
            if (empty($v[2])) continue;

            $project = ProjectModel::where('project_name', $v[2])
                ->where('is_parent', 1)
                ->find();
            if (empty($project)) {
                $error_array[] = '第' . $i .  '行项目名称异常';
                continue;
            }

            $zrr = ProjectZrrModel::where('project_id', $project->id)
                ->where('dw_name', $v[3])
                ->find();
            if (empty($zrr)) {
                $error_array[] = '第' . $i .  '行单位信息异常';
                continue;
            }

            $project_id = $project->id;
            $link_id = $zrr->id;

            $insert_array[] = [
                'project_name' => $v[2],
                'zrr_name' => $v[4] ?: null,
                'zrr_position' => $v[5] ?: null,
                'zrr_tel' => $v[6] ?: null,
                'zrr_identity' => $v[7] ?: null,
                'project_id' => $project_id,
                'link_id' => $link_id,
                'score' => '100',
                'status' => '1',
            ];
        }

        (!empty($error_array)) && $this->error('上传异常：' . implode('，', $error_array));

        try {
            (new ProjectZrrDetailModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }

    /**
     * 获取列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list()
    {
        $input = $this->request->param();
        $page_size = input('pageSize', '20');
        $data = ProjectZrrDetailModel::where('1=1');

        if (!empty($input['zrr_name'])) {
            $data->where('zrr_name', 'like', '%' . $input['zrr_name'] . '%');
        }
        if (!empty($input['zrr_tel'])) {
            $data->where('zrr_tel', 'like', '%' . $input['zrr_tel'] . '%');
        }
        if (!empty($input['zrr_identity'])) {
            $data->where('zrr_identity', 'like', '%' . $input['zrr_identity'] . '%');
        }
        if (!empty($input['project_name'])) {
            $data->where('project_name', 'like', '%' . $input['project_name'] . '%');
        }
        if (!empty($input['project_id'])) {
            $data->where('project_id', '=', $input['project_id']);
        }

        $data = $data->paginate($page_size);

        if (empty($data)) $this->error('查询数据为空');

        $this->success('success', $data);
    }

    /**
     * 导出默认模板
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function export()
    {
        $project_id = input('project_id/s', '');
        empty($project_id) && $this->error('请传入id');

        $spreadsheet = new Spreadsheet();

        // sheet0
        $worksheet = $spreadsheet->getSheet(0);
        // 设置工作表标题名称
        $worksheet->setTitle('提示');
        // 设置表信息
        $worksheet->setCellValueByColumnAndRow(1, 1, '提示');
        $worksheet->getColumnDimension('B')->setWidth(75);
        $worksheet->setCellValueByColumnAndRow(2, 1, '名称保持一致；会把职位默认有一个在模板里；单个职位多个人自行插入添加');
        $worksheet->setCellValueByColumnAndRow(2, 2, '填写的时候请确认是否录入单位（pc-单体-详情-队伍管理录入单位 ）');
        $worksheet->setCellValueByColumnAndRow(2, 3, '填写名称的时候则确认单位和职位不能错误');
        $worksheet->setCellValueByColumnAndRow(2, 4, '人员录入在第excel表二个页签录入');

        // sheet1
        $spreadsheet->createSheet(1);
        $worksheet = $spreadsheet->getSheet(1);
        // 设置工作表标题名称
        $worksheet->setTitle('人员导入模板');
        // 表头
        $worksheet->setCellValueByColumnAndRow(1, 1, '序号');
        $worksheet->setCellValueByColumnAndRow(2, 1, '项目名称');
        $worksheet->setCellValueByColumnAndRow(3, 1, '单体工程名称');
        $worksheet->setCellValueByColumnAndRow(4, 1, '单位名称');
        $worksheet->setCellValueByColumnAndRow(5, 1, '姓名');
        $worksheet->setCellValueByColumnAndRow(6, 1, '人员角色/专职名称');
        $worksheet->setCellValueByColumnAndRow(7, 1, '电话');
        $worksheet->setCellValueByColumnAndRow(8, 1, '身份证号');

        $worksheet->getColumnDimension('B')->setWidth(40);
        $worksheet->getColumnDimension('c')->setWidth(30);
        $worksheet->getColumnDimension('D')->setWidth(45);
        $worksheet->getColumnDimension('E')->setWidth(15);
        $worksheet->getColumnDimension('F')->setWidth(20);
        $worksheet->getColumnDimension('G')->setWidth(20);
        $worksheet->getColumnDimension('H')->setWidth(25);

        $worksheet->getStyle('E1')->getFill()->setFillType(Fill::FILL_SOLID)
            ->getStartColor()->setARGB(Color::COLOR_YELLOW);
        $worksheet->getStyle('G1')->getFill()->setFillType(Fill::FILL_SOLID)
            ->getStartColor()->setARGB(Color::COLOR_YELLOW);
        $worksheet->getStyle('H1')->getFill()->setFillType(Fill::FILL_SOLID)
            ->getStartColor()->setARGB(Color::COLOR_YELLOW);

        $project = ProjectModel::where('id', $project_id)
            ->field(['id', 'link_project_id'])
            ->find();
        if (empty($project)) $this->error('无效的项目');
        $father_project = ProjectModel::where('id', $project->link_project_id)
            ->field(['id', 'project_name'])
            ->find();
        if (empty($father_project)) $this->error('项目数据异常');

        $unit = ProjectZrrModel::where('project_id', $project_id)
            ->select();
        if (empty($unit)) $this->error('未找到符合条件的单位');

        $row = 2;
        foreach ($unit as $v) {
            switch ($v['dw_type']) {
                case '劳务分包':
                case '专业分包':
                    $type = '施工单位=>' . $v['dw_type'];
                    break;
                case '施工单位':
                    $type = '施工单位=>自有单位';
                    break;
                default:
                    $type = $v['dw_type'];
            }

            $position_array = \app\app\controller\ProjectZrr::getPersonLiableDefaultArray($type);

            foreach ($position_array as $x => $y) {
                $worksheet->setCellValueByColumnAndRow(1, $row, $row - 1);
                $worksheet->setCellValueByColumnAndRow(2, $row, $father_project->project_name);
                $worksheet->setCellValueByColumnAndRow(3, $row, $v->project_name);
                $worksheet->setCellValueByColumnAndRow(4, $row, $v->dw_name);
                $worksheet->setCellValueByColumnAndRow(5, $row, '');
                $worksheet->setCellValueByColumnAndRow(6, $row, $x);
                $worksheet->setCellValueByColumnAndRow(7, $row, '');
                $worksheet->setCellValueByColumnAndRow(8, $row, '');

//                $worksheet->getStyle('E' . $row)->getFill()->setFillType(Fill::FILL_SOLID)
//                    ->getStartColor()->setARGB(Color::COLOR_YELLOW);
//                $worksheet->getStyle('G' . $row)->getFill()->setFillType(Fill::FILL_SOLID)
//                    ->getStartColor()->setARGB(Color::COLOR_YELLOW);
//                $worksheet->getStyle('H' . $row)->getFill()->setFillType(Fill::FILL_SOLID)
//                    ->getStartColor()->setARGB(Color::COLOR_YELLOW);

                $row++;
            }

        }

        $filename = '人员导入模板.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

        $this->success('success');
    }

    /**
     * 违章库导入
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function violationImport()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'zrr', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name, 0);

        $insert_array = [];
        $error_array = [];
        $i = 0;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;

            $project = ProjectModel::where('project_name', $v[3])
                ->where('is_parent', 1)
                ->field(['id', 'project_name'])
                ->find();
            if (empty($project)) {
                $error_array[] = '第' . $i .  '行工程名称异常';
                continue;
            }

            $content = $v[5];
//            $level = $v[7];
//            $type = $v[8];

            $zrr_name_index = [9, 13, 15, 17, 19, 21, 25, 27, 31, 33, 35, 37];

            $zrr_name = array_map(function ($a) use($v) {
                return $v[$a];
            }, $zrr_name_index);
            $zrr_name = array_filter($zrr_name);

            if (empty($zrr_name)) continue;

            $zrr_detail = ProjectZrrDetailModel::where('zrr_name', 'in', $zrr_name)
                ->where('project_id', $project->id)
                ->select();
            $zrr = array_column($zrr_detail->toArray(), null, 'zrr_name');

            foreach ($zrr_name_index as $a) {

                if (empty($v[$a])) {
                    continue;
                }
                if (empty($zrr[$v[$a]])) {
                    $error_array[] = '第' . $i .  '行第'. ($a + 1) .'列责任人信息异常';
                    continue;
                }

                $b = $a + 1;
                $score = 0;
                if (!empty($v[$b])) {
                    $score = $v[$b];
                }

                $insert_array[] = [
                    'project_id' => $project->id,
                    'project_name' => $project->project_name,
                    'zrr_detail_id' => $zrr[$v[$a]]['id'],
                    'content' => $content,
                    'score' => $score,
//                    'level' => $level,
//                    'type' => $type,
                    'create_time' => date('Y-m-d H:i:s'),
                ];

                $last_score = floatval(($zrr[$v[$a]]['violation_score'] ?: 100)) - floatval($score);
                $last_score = round($last_score, 2);
                ProjectZrrDetailModel::where('id', $zrr[$v[$a]]['id'])->update(['violation_score' => $last_score]);
            }
        }

        if (!empty($error_array)) {
            $error_msg = implode('，', $error_array);
            $this->error('导入失败：' . $error_msg);
        }

        try {
            Db::table('t_project_violation')->insertALl($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('导入成功');
    }
}